﻿using System.Device.Location;
using Amicus_Place_Finder;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

public static class FoursquareAPI
{
    public const string ClientId = "UXWSTBJHFHJEF2S25BJ2TUXDIRLOIQ0AWZ4D4WUNXRM1NKY1";
    public const string ClientSecret = "EBO4POTQRBOXGIGRMRACO1BAYOV122FGDVBDEPQYYGSWVU3M";
    public static string AccessToken = "FJ432CDDGBOFQSPRUURWDUVFLL24BZVT52C2ZWP5OJ21I5D0";

    public const string AccessTokenUrl = "https://foursquare.com/oauth2/access_token";
    public const string AuthorizeUrl = "https://foursquare.com/oauth2/authorize";
    public const string RedirectUri = "http://www.facebook.com/TeamAmicus/redirect";

    public const string SearchQuery = "https://api.foursquare.com/v2/venues/search?ll={0},{1}&oauth_token={2}&v={3}&radius={4}";
    public const string SearchQueryWithKeywork = "https://api.foursquare.com/v2/venues/search?ll={0},{1}&oauth_token={2}&v={3}&query={4}&radius={5}";
    public const string CategoryQuery = "&categoryId={0}";
    public static string[] Categories = { "4bf58dd8d48988d1f9941735", "4d4b7105d754a06374d81259" };

    public static void GetAccessToken()
    {
    }

    public static async Task<List<PlaceItem>> GetNearbyPlaces(double lat, double lng, bool category = false)
    {
        try
        {
            if (AccessToken == "")
                GetAccessToken();
            var wc = new WebClient();
            var l = string.Format(SearchQuery,
                                    lat,
                                    lng,
                                    AccessToken,
                                    DateTime.Now.ToString("yyyyMMdd"),
                                    SettingUtils.Settings.MapSearchRadius);
            if (category)
                l = string.Format(l + "CategoryQuery", String.Join(",", Categories));
            Debug.WriteLine(l);
            var r = await wc.DownloadStringTaskAsync(l);
            return ParsePlaceItem(r);
        }
        catch { return ParsePlaceItem(""); }
    }

    public static async Task<List<PlaceItem>> GetPlaces(string name, double lat, double lng, bool category = false)
    {
        try
        {
            if (AccessToken == "")
                GetAccessToken();
            var wc = new WebClient();
            var l = string.Format(SearchQueryWithKeywork,
                                    lat,
                                    lng,
                                    AccessToken,
                                    DateTime.Now.ToString("yyyyMMdd"),
                                    name,
                                    SettingUtils.Settings.MapSearchRadius);
            if (category)
                l = string.Format(l + "CategoryQuery", String.Join(",", Categories));
            Debug.WriteLine(l);
            var r = await wc.DownloadStringTaskAsync(l);
            return ParsePlaceItem(r);
        }
        catch { return ParsePlaceItem(""); }
    }

    public static async Task<List<PlaceItem>> GetNearbyPlaces(GeoCoordinate gps)
    {
        return await GetNearbyPlaces(gps.Latitude, gps.Longitude);
    }

    private static string TryToGetNode(JObject item, string node)
    {
        try
        {
            return (string)item["address"];
        }
        catch
        {
            return "";
        }
    }

    private static string TryToGetIcon(JObject item)
    {
        try
        {
            var prefix = (string) item["categories"][0]["icon"]["prefix"];
            //prefix = prefix.Substring(0, prefix.Length - 1);
            var suffix = (string) item["categories"][0]["icon"]["suffix"];
            return prefix + "64" + suffix;
        }
        catch
        {
            return "";
        }
    }

    //private static List<FoursquarePlaceItem> ParsePlaceItem(string r)
    //{
    //    var list = new List<FoursquarePlaceItem>();
    //    try
    //    {
    //        var jo = JObject.Parse(r);
    //        foreach (JObject item in (JArray)jo["response"]["venues"])
    //        {
    //            try
    //            {
    //                list.Add(new FoursquarePlaceItem
    //                {
    //                    Id = (string)item["id"],
    //                    Name = (string)item["name"],
    //                    Icon = new BitmapImage(new Uri(TryToGetIcon(item))),
    //                    Url = (string)item["canonicalUrl"],
    //                    address = TryToGetNode((JObject)item["location"], "address"),
    //                    cc = (string)item["location"]["cc"],
    //                    city = (string)item["location"]["city"],
    //                    country = (string)item["location"]["country"],
    //                    lat = (double)item["location"]["lat"],
    //                    lng = (double)item["location"]["lng"],
    //                    distance = (double)item["location"]["distance"],
    //                    state = (string)item["location"]["state"]
    //                });
    //            }
    //            catch (Exception ex) { Debug.WriteLine(ex.Message); }
    //        }
    //    }
    //    catch (Exception e) { Debug.WriteLine(e.Message); }
    //    return list;
    //}

    private static List<PlaceItem> ParsePlaceItem(string r)
    {
        var list = new List<PlaceItem>();
        try
        {
            var jo = JObject.Parse(r);
            int count = 0;
            foreach (JObject item in (JArray)jo["response"]["venues"])
            {
                count++;
                try
                {
                    list.Add(new PlaceItem
                    {
                        ID = count,
                        Id = (string)item["id"],
                        Name = (string)item["name"],
                        Icon = new BitmapImage(new Uri(TryToGetIcon(item))),
                        Url = (string)item["canonicalUrl"],
                        address = TryToGetNode((JObject)item["location"], "address"),
                        //cc = (string)item["location"]["cc"],
                        city = (string)item["location"]["city"],
                        country = (string)item["location"]["country"],
                        latitude = (double)item["location"]["lat"],
                        longitude = (double)item["location"]["lng"],
                        distance = (double)item["location"]["distance"],
                        state = (string)item["location"]["state"]
                    });
                }
                catch (Exception ex) { Debug.WriteLine(ex.Message); }
            }
        }
        catch (Exception e) { Debug.WriteLine(e.Message); }
        return list;
    }
}

public class FoursquarePlaceItem
{
    public string Id { get; set; }

    public string Name { get; set; }

    public BitmapImage Icon { get; set; }

    public string Url { get; set; }

    public string address { get; set; }

    public string cc { get; set; }

    public string city { get; set; }

    public string country { get; set; }

    public double distance { get; set; }

    public double lat { get; set; }

    public double lng { get; set; }

    public string state { get; set; }
}
